<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="rrext_option_config.js"></script>
<script type="text/javascript">

var ACTION = {};
ACTION.tab = ACTION.tab || {};

ACTION.tab.showPageActionIcon = function() {
	chrome.pageAction.show(this.id);
};

ACTION.writeClipboard = function(text) {
	var copyTextarea = document.querySelector('#rrext_copyTextarea');
	copyTextarea.innerHTML = text;
	copyTextarea.select();
	copyTextarea.focus();
	if (!document.execCommand('copy')) {
		throw new Error('Copy Failed');
	}
};

ACTION.getOption = function() {
	var optionNames = Array.prototype.slice.call(arguments, 0);
	var optionValues = {};
	if (optionNames.length > 0) {
		optionNames.forEach(function(optionName){
			if (rrext.OPTION[optionName]) {
				optionValues[optionName] = rrext.OPTION[optionName].read();
			}
		});
	} else {
		var options = rrext.OPTION();
		for (var i in options) {
			optionValues[options[i].name] = options[i].read();
		}
	}
	if (optionNames.length == 1) {
		return optionValues[optionNames[0]];
	} else {
		return optionValues;
	}
};
ACTION.setOption = function(optionName, optionValue) {
	if (rrext.OPTION[optionName]) {
		return rrext.OPTION[optionName].write(optionValue);
	} 
	throw new Error('['+optionName+'] is invalid option name.');
};

chrome.extension.onRequest.addListener(
	function(data, sender, sendResponse) {
		try {
			var action = data.action;
			//console.debug("action:" + action);
			if (ACTION.tab[action]) {
				var args = data.args || [];
				//console.debug("args:", args);
				if (sender.tab) {
					//console.debug("tab:", sender.tab);
					var ret = ACTION.tab[action].apply(sender.tab, data.args);
					if (!(ret instanceof Array)) ret = [ret];
					if (sendResponse) sendResponse.apply(null, ret);
				} else {
					throw new Error('action['+action+'] is not tab action.');
				}
			} else if (ACTION[action]) {
				var args = data.args || [];
				//console.debug("args:", args);
				var ret = ACTION[action].apply(null, data.args);
				if (!(ret instanceof Array)) ret = [ret];
				if (sendResponse) sendResponse.apply(null, ret);
			} else {
					throw new Error('action['+action+'] is not found.');
			}
		} catch(e) {
			console.error("error:" + e);
			if (data.errback) data.errback.apply(null, e);
		}
	}
);


chrome.browserAction.onClicked.addListener(function(tab){
	chrome.tabs.create({
		url: (rrext.OPTION['EnableSsl'].read() ? 'https' : 'http') + '://ringreef.com/group/',
		selected: true,
		index: tab.index + 1,
	});
});

</script>
</head>
<body>
<textarea id="rrext_copyTextarea"></textarea>
</body>
</html>
